package com.examination.controller.utils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

/**
 * @Auther: GongXl
 * @Date: 010 13:47
 * @Description:
 */
@WebServlet("/DownloadServlet")
public class DownloadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        String fileName = request.getParameter("fileName");
        response.setContentType("image/png");
        response.setHeader("Content-Disposition","attachment;filename="+fileName);
        //那个文件
        String filePath = this.getServletContext().getRealPath("/files/"+fileName);
        //文件流输出
        ServletOutputStream outputStream = response.getOutputStream();
        InputStream in = new FileInputStream(filePath);
        byte[] buff  = new byte[1024];//1k读文件
        int len = 0;
        while ((len = in.read(buff)) > 0){
            outputStream.write(buff,0,len);
        }
        outputStream.flush();
        outputStream.close();

//        request.getRequestDispatcher("/files/logo1.png").forward(request,response);

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}